﻿using System.Linq;
using System.Web;
using Newtonsoft.Json;
using SBACN.WebSite.Cache;
using SBACN.WebSite.Code;
using SBACN.WebSite.Models;
using System.Collections.Generic;

namespace SBACN.WebSite.Handler.Admin
{
	/// <summary>
	/// RoleHandler 的摘要说明
	/// </summary>
	public class RoleHandler : BaseHandler
	{
		public override void Process()
		{
			HttpContext context = base.httpContext;
			context.Response.Charset = "UTF-8";
			context.Response.ContentType = "text/json";
			int roleID = 0;
			if (!string.IsNullOrWhiteSpace(context.Request["rid"]) && int.TryParse(context.Request["rid"], out roleID))
			{
				var roleRightList = RoleRightCache.Instance.CacheList.Where(p => p != null && p.RoleID == roleID).Select(p => new { Code = p.Code, RoleID = p.RoleID, Type = p.Type }).ToList();
				string json = JsonConvert.SerializeObject(roleRightList);
				context.Response.Write(json);
			}

			if (!string.IsNullOrWhiteSpace(context.Request["ri"]) && int.TryParse(context.Request["ri"], out roleID))
			{
				var roleInfo = RoleCache.Instance.CacheList.Where(p => p != null && p.ID == roleID).Select(p => new { RoleName = p.Name, Description = p.Description, Status = p.Status, Editable = p.Editable }).FirstOrDefault();
				string json = JsonConvert.SerializeObject(roleInfo);
				context.Response.Write(json);
			}

			if(!string.IsNullOrWhiteSpace(context.Request["un"]))
			{
				var user = DAL.DALHelper.Instance.GetObject<TB_User>("UserName",context.Request["un"].ToLower().Trim());
				if(user != null)
				{
					var userRole = UserRightCache.Instance[user.UserName].FirstOrDefault();
					var jsonUser = new { Name = user.UserName, NickName = user.NickName ?? string.Empty, EMail = user.EMail ?? string.Empty, MemberID = user.MemberID, RoleID = userRole == null ? 0 : userRole.RoleID, Status = user.Status };
				if(user != null)
				{
					string json = JsonConvert.SerializeObject(jsonUser);
					context.Response.Write(json);
				}
				}
			}
			context.Response.End();
		}

		public string GetList()
		{
			return JsonConvert.SerializeObject(RoleRightCache.Instance.CacheList.Select(p => new { RoleName = p.RoleName, URL = p.URL, Type = p.Type }));
		}

		public string GetObject(string roleName)
		{
			var entity = RoleRightCache.Instance.CacheList.Where(p => p.RoleName == roleName).Select(p => new { RoleName = p.RoleName, URL = p.URL, Type = p.Type }).FirstOrDefault();
			return JsonConvert.SerializeObject(entity);
		}
	}
}